<!--分散式房源编辑表单-->
<template>
	<a-form ref="form" class="house-form-base" :model="house" :rules="rules" layout="vertical" scroll-to-first-error>
		<a-typography-text strong>
			<!-- <blockquote>房源模式</blockquote> -->
			<blockquote>经营模式</blockquote>
		</a-typography-text>
		<a-form-item name="houseBizMode">
			<a-radio-group
				v-model:value="house.houseBizMode"
				:disabled="house.houseBizMode === 1 && houseBizModeDisabled"
				class="custom-radio-group">
				<a-radio-button v-for="item in houseBizModeList" :key="item.value" :value="item.value">
					<a-typography-paragraph>{{ item.label }}</a-typography-paragraph>
					<a-typography-text type="secondary">
						<small>{{ item.desc }}</small>
					</a-typography-text>
				</a-radio-button>
			</a-radio-group>
		</a-form-item>
		<a-typography-text strong>
			<blockquote>房源信息</blockquote>
		</a-typography-text>
		<a-skeleton :loading="loading.load" active :paragraph="{rows: 6}">
			<a-row :gutter="16">
				<a-col :span="6">
					<a-form-item label="房源编号：" name="houseNo">
						<a-input v-model:value="house.houseNo" allow-clear :maxlength="15" placeholder="请输入房源编号" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="城市：" name="cityId">
						<a-select v-model:value="house.cityId" v-bind="cityOptions" />
					</a-form-item>
				</a-col>
				<a-col :span="10">
					<a-form-item label="小区：" name="communityId">
						<a-select
							v-model:value="house.communityId"
							v-bind="communityOptions"
							:disabled="!house.cityId"
							:placeholder="house.cityId ? '请选择小区' : '请先选择城市'">
							<template #dropdownRender="{menuNode}">
								<component :is="menuNode" />
								<a-divider style="margin: 4px 0" />
								<a-button class="text-left" type="link" size="small" block @click="onClickToAddCommunity">
									找不到小区？点击这里添加小区
								</a-button>
							</template>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="门牌号：" name="location">
						<a-input-group compact style="display: flex">
							<a-form-item-rest>
								<a-input v-model:value="house.buildingNo" :maxlength="6" placeholder="请输入" style="flex: 1" />
								<a-auto-complete v-model:value="house.buildingNoSuffix" :options="buildingSuffixes" style="width: 80px">
									<template #default>
										<a-input>
											<template #suffix>
												<down-outlined style="font-size: 12px; color: rgba(0, 0, 0, 0.25)" />
											</template>
										</a-input>
									</template>
								</a-auto-complete>
								<a-input v-model:value="house.unit" :maxlength="6" suffix="单元" placeholder="请输入" style="flex: 1" />
								<a-input v-model:value="house.doorplate" :maxlength="6" suffix="号" placeholder="请输入" style="flex: 1" />
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="楼层：" name="floor">
						<a-form-item-rest>
							<a-input-group compact style="display: flex">
								<a-input-number
									v-model:value="house.totalFloor"
									:min="1"
									:max="99"
									:precision="0"
									prefix="共"
									addonAfter="层"
									placeholder="请输入"
									style="flex: 1" />
								<a-input-number
									v-model:value="house.currentFloor"
									:min="1"
									:max="house.totalFloor"
									:precision="0"
									prefix="第"
									addonAfter="层"
									placeholder="请输入"
									style="flex: 1" />
							</a-input-group>
						</a-form-item-rest>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="朝向：" name="orientation">
						<a-select
							v-model:value="house.orientation"
							:options="orientationList"
							allow-clear
							show-search
							placeholder="请选择朝向" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="户型：" name="roomType">
						<a-input-group compact style="display: flex">
							<a-form-item-rest>
								<a-input-number
									v-model:value="house.room"
									:disabled="[2, 3].includes(talentedHouseStatus)"
									:min="0"
									:maxlength="2"
									:precision="0"
									addonAfter="室"
									placeholder="请输入"
									@change="house.userlimit = house.room"
									style="flex: 1" />
								<a-input-number
									v-model:value="house.livingRoom"
									:disabled="[2, 3].includes(talentedHouseStatus)"
									:min="0"
									:maxlength="2"
									:precision="0"
									addonAfter="厅"
									placeholder="请输入"
									style="flex: 1" />
								<a-input-number
									v-model:value="house.toliet"
									:disabled="[2, 3].includes(talentedHouseStatus)"
									:min="0"
									:maxlength="2"
									:precision="0"
									addonAfter="卫"
									placeholder="请输入"
									style="flex: 1" />
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="可住人数：" name="userlimit">
						<a-input-number
							v-model:value="house.userlimit"
							:min="1"
							:precision="0"
							:default-value="house.room"
							placeholder="请输入" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="面积：" name="houseArea">
						<a-input-number v-model:value="house.houseArea" :min="0" :precision="2" addonAfter="㎡" placeholder="请输入" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="装修：" name="fitmentType">
						<a-select
							v-model:value="house.fitmentType"
							:options="fitmentTypes"
							:field-names="DEFAULT_FIELD_NAME"
							allow-clear
							show-search
							placeholder="请选择装修类型" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-skeleton>
		<a-typography-text strong>
			<blockquote>附加信息</blockquote>
		</a-typography-text>
		<a-skeleton :loading="loading.load" active>
			<a-row :gutter="16">
				<a-col :span="4">
					<a-form-item label="用水：">
						<a-select v-model:value="house.waterType" :options="waterTypeList" allow-clear placeholder="请选择" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="用电：">
						<a-select v-model:value="house.electricityType" :options="elecTypeList" allow-clear placeholder="请选择" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="燃气：">
						<a-select v-model:value="house.gasType" :options="gasTypeList" allow-clear placeholder="请选择" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="供暖：">
						<a-select v-model:value="house.heatingType" :options="heatingTypeList" allow-clear placeholder="请选择" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="看房时间：">
						<a-select v-model:value="house.viewType" :options="viewTypeList" allow-clear placeholder="请选择" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-skeleton>
		<a-typography-text strong>
			<blockquote>房屋整租价格</blockquote>
		</a-typography-text>
		<a-skeleton :loading="loading.load" active>
			<a-row :gutter="16">
				<a-col :span="4">
					<a-form-item label="出租价（元）：" name="actualPrice">
						<a-input-number
							v-model:value="house.actualPrice"
							:min="0"
							:precision="2"
							addonAfter="元"
							placeholder="请输入出租价"
							@change="house.basePrice = house.actualPrice" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="底价（元）：" name="basePrice">
						<a-input-number
							v-model:value="house.basePrice"
							:min="0"
							:max="house.actualPrice"
							:precision="2"
							addonAfter="元"
							placeholder="请输入底价" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="房型押金(元)：" name="depositPrice">
						<a-input-number
							v-model:value="house.depositPrice"
							:min="0"
							:precision="2"
							addon-after="元"
							placeholder="请输入底价" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="房型物业费(元)：" name="propertyPrice">
						<a-input-number
							v-model:value="house.propertyPrice"
							:min="0"
							:precision="2"
							addon-after="元"
							placeholder="请输入底价" />
					</a-form-item>
				</a-col>
				<a-col :span="4" v-if="house.houseBizMode == 1">
					<a-form-item label="收房价（元）：" name="costPrice">
						<a-input-number
							v-model:value="house.costPrice"
							:min="0"
							:max="999999999.99"
							:precision="2"
							addonAfter="元"
							placeholder="请输入收房价" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="可租日期：">
						<a-date-picker
							v-model:value="house.avaliableDate"
							allow-clear
							:value-format="DATE_FORMAT.DATE"
							placeholder="请选择可租日期" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-skeleton>

		<template v-if="house.houseType === 2">
			<a-typography-text strong>
				<blockquote>房源子间</blockquote>
			</a-typography-text>

			<vxe-table ref="roomsTable" :data="house.roomList" v-bind="tableOptions">
				<vxe-column field="roomName" min-width="120px" align="center">
					<template #header>
						<a-typography-text type="danger">*</a-typography-text>
						房间名称
					</template>
					<template #default="{row, rowIndex}">
						<a-form-item :name="['roomList', rowIndex, 'roomName']" required>
							<a-input v-model:value="row.roomName" :maxlength="10" placeholder="请输入" />
						</a-form-item>
					</template>
				</vxe-column>
				<vxe-column min-width="120px" align="center">
					<template #header>
						<a-typography-text type="danger">*</a-typography-text>
						朝向
					</template>
					<template #default="{row, rowIndex}">
						<a-form-item :name="['roomList', rowIndex, 'orientation']" required>
							<a-select v-model:value="row.orientation" :options="orientationList" />
						</a-form-item>
					</template>
				</vxe-column>
				<vxe-column min-width="120px" align="center">
					<template #header>
						<a-typography-text type="danger">*</a-typography-text>
						面积（㎡）
					</template>
					<template #default="{row, rowIndex}">
						<a-form-item :name="['roomList', rowIndex, 'houseArea']" required>
							<a-input-number v-model:value="row.houseArea" :min="0" :precision="2" placeholder="请输入" />
						</a-form-item>
					</template>
				</vxe-column>
				<vxe-column min-width="120px" align="center">
					<template #header>
						<a-typography-text type="danger">*</a-typography-text>
						出租价（元）
					</template>
					<template #default="{row, rowIndex}">
						<a-form-item :name="['roomList', rowIndex, 'actualPrice']" required>
							<a-input-number
								v-model:value="row.actualPrice"
								:min="0"
								:precision="2"
								@change="row.basePrice = row.actualPrice"
								placeholder="请输入" />
						</a-form-item>
					</template>
				</vxe-column>
				<vxe-column min-width="120px" align="center">
					<template #header>
						<a-typography-text type="danger">*</a-typography-text>
						底价（元）
					</template>
					<template #default="{row, rowIndex}">
						<a-form-item :name="['roomList', rowIndex, 'basePrice']" required>
							<a-input-number
								v-model:value="row.basePrice"
								:min="0"
								:max="row.actualPrice"
								:precision="2"
								placeholder="请输入" />
						</a-form-item>
					</template>
				</vxe-column>
				<!-- <vxe-column min-width="120px" align="center" v-if="house.houseBizMode == 1">
					<template #header>
						<a-typography-text type="danger">*</a-typography-text>
						收房价（元）
					</template>
					<template #default="{row, rowIndex}">
						<a-form-item :name="['roomList', rowIndex, 'basePrice']" required>
							<a-input-number v-model:value="row.basePrice" :min="0" :max="999999999.99" :precision="2" placeholder="请输入" />
						</a-form-item>
					</template>
				</vxe-column> -->
				<vxe-column title="可租日期" min-width="150px" align="center">
					<template #default="{row, rowIndex}">
						<a-form-item :name="['roomList', rowIndex, 'avaliableDate']">
							<a-date-picker v-model:value="row.avaliableDate" :value-format="DATE_FORMAT.DATE" placeholder="请选择" />
						</a-form-item>
					</template>
				</vxe-column>
				<vxe-column title="可住人数" min-width="120px" align="center">
					<template #default="{row, rowIndex}">
						<a-form-item :name="['roomList', rowIndex, 'userlimit']">
							<a-input-number v-model:value="row.userlimit" :min="0" :precision="0" :default-value="1" placeholder="请输入" />
						</a-form-item>
					</template>
				</vxe-column>
				<vxe-column key="action" title="操作" width="100px" align="center" fixed="right">
					<template v-if="house.roomList && house.roomList.length > 2" #default="{row, rowIndex}">
						<a-button type="link" danger size="small" @click="onClickToDelRoom(row, rowIndex)">
							<a-tooltip title="删除房间">
								<delete-outlined />
							</a-tooltip>
						</a-button>
					</template>
				</vxe-column>
			</vxe-table>
			<a-form-item name="roomList" class="room-table-validator" />
			<a-button type="primary" ghost block @click="onClickToAddRoom" style="border-style: dashed">
				<plus-outlined />
				添加子间
			</a-button>
		</template>
		<a-typography-text strong>
			<blockquote>房源归属</blockquote>
		</a-typography-text>
		<a-row :gutter="16">
			<a-col :span="12">
				<a-form-item label="部门(门店)/维护人：" name="stewardId">
					<dept-emp-select v-model:dept-id="house.deptId" v-model:emp-id="house.stewardId" only-store />
				</a-form-item>
			</a-col>
		</a-row>
	</a-form>
	<teleport v-if="visibles.footer" to=".house-edit-dialog .ant-modal-footer">
		<a-button type="primary" :loading="loading.save" @click="saveHouseBase()">保存</a-button>
		<a-button v-if="house.id" :loading="loading.save" @click="saveHouseBase(true)">下一步，完善推广信息</a-button>
	</teleport>
	<house-community-map v-model:visible="visibles.map" :value="community" @close="communityMapClose" />
</template>

<script lang="ts" setup>
	import {createVNode, onMounted, reactive, ref, toRef, watchEffect} from 'vue'
	import {
		buildingSuffixes,
		defaultRoom,
		elecTypeList,
		gasTypeList,
		heatingTypeList,
		HouseBase,
		houseBizModeList,
		HouseRoom,
		orientationList,
		viewTypeList,
		waterTypeList
	} from '@/interface/house'
	import houseApi from '@/api/house-api'
	import {ownerContractCheckValid} from '@/api/contract'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {houseBaseRules} from '@/rules/house'
	import {DownOutlined, PlusOutlined, QuestionCircleOutlined, DeleteOutlined} from '@ant-design/icons-vue'
	import {message, Modal} from 'ant-design-vue'
	import {DEFAULT_FIELD_NAME, DIC_PID_MAP} from 'yuxin-base/src/constant'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import {Community} from '@/interface/community'
	import {findSelf} from '@/utils'
	import HouseCommunityMap from '@/components/house/edit/house-community-map.vue'
	import {FormExpose} from 'ant-design-vue/lib/form/Form'
	import {VxeTableInstance, VxeTableProps} from 'vxe-table'
	import {useStore} from '@/store/index'
	const hasPermissions = useStore().hasPermissions
	const rules = ref({})

	const props = defineProps<{
		value: HouseBase
	}>()

	const form = ref<FormExpose>()
	const emits = defineEmits(['next'])

	const loading = reactive({
		save: false,
		load: false
	})

	const visibles = reactive({
		map: false,
		footer: false
	})

	onMounted(async () => {
		// console.log(house, props.value, '传递过来的是多少')
		visibles.footer = true

		if (!house.value.id) {
			const rooms = house.value.roomList || []
			if (originHouse.value.houseType === 2 && rooms.length === 0) {
				// 根据几室自动生成子间
				for (let i = 0; i < (house.value.room || 1); i++) {
					onClickToAddRoom()
				}
			}
		}
		getPropertyCertificationF(house.value.id || house.value.housePid)
		settingApi.getCityList().then(({data}) => (cities.value = data))


		// 82308字典修改 新增查使用中 编辑查全部
		let action = props.value?.id ? settingApi.getDicListByPidAll : settingApi.getDicListByPid
		action(DIC_PID_MAP['HOUSE@DECORTYPE']).then(({data}) => (fitmentTypes.value = data))

		if (house.value.houseBizMode == 1) {
			getOwnerContractCheckValid()
		}
		//todo
		const res = await settingApi.getDecisionList({bizPoint: 'HOUSE_SETTING', module: 'HOUSE'})
		let source = JSON.parse(res.data[0]?.value || '[]')
		if(source.includes(1)) rules.value.depositPrice = [{required: true, message: '请输入押金'}]
		if(source.includes(2)) rules.value.propertyPrice = [{required: true, message: '请输入物业费'}]
		rules.value = {
			...rules.value,
			...houseBaseRules(house.value)
		}
	})
	const houseBizModeDisabled = ref<boolean>(false)
	const getOwnerContractCheckValid = () => {
		ownerContractCheckValid(house.value.communityId, house.value.housePid).then(res => {
			houseBizModeDisabled.value = res.data
			console.log(res, '是否有业主合同')
		})
	}
	// 获取房源认证状态
	const talentedHouseStatus = ref<number>(0)
	const getPropertyCertificationF = id => {
		if (!id) return
		houseApi.getPropertyCertification(id as string).then(({data}) => {
			talentedHouseStatus.value = data.talentedHouseStatus
		})
	}
	const house = ref<HouseBase>(props.value)
	const originHouse = toRef(props, 'value')
	if (house.value.id && house.value.housePid) {
		loading.load = true
		// 获取房源详情
		houseApi
			.getHouseBaseInfo(house.value.housePid)
			.then(({data}) => {
				Object.assign(house.value, data)

				// 合整租转换
				if (originHouse.value.transform) {
					house.value.transform = originHouse.value.transform
					house.value.houseType = originHouse.value.houseType

					const rooms = house.value.roomList || []
					if (originHouse.value.houseType === 2 && rooms.length === 0) {
						// 根据几室自动生成子间
						for (let i = 0; i < (house.value.room || 1); i++) {
							onClickToAddRoom()
						}
					}
				}
			})
			.finally(() => (loading.load = false))
	}

	// 城市列表
	const cities = ref<any>([])
	const cityOptions = reactive<any>({
		options: cities,
		allowClear: true,
		showSearch: true,
		placeholder: '请选择城市',
		optionFilterProp: 'name',
		fieldNames: DEFAULT_FIELD_NAME
	})

	// 小区列表
	const communities = ref<Community[]>([])
	const communityOptions = reactive<any>({
		options: communities,
		allowClear: true,
		showSearch: true,
		optionFilterProp: 'name',
		fieldNames: DEFAULT_FIELD_NAME,
		onSearch(keyword: string) {
			community.value.name = keyword
		}
	})
	watchEffect(() => {
		if (house.value.cityId) {
			houseApi.getCommunityList({type: 1, cityId: house.value.cityId}).then(({data}) => {
				communities.value = data
				if (!data.map((o: any) => o.id).includes(house.value.communityId)) {
					house.value.communityId = null
				}
			})
		} else {
			communities.value = []
			house.value.communityId = null
		}
	})

	// 房间编辑表格配置
	const tableOptions = reactive<VxeTableProps>({
		size: 'small',
		maxHeight: 300,
		rowClassName: 'house-room-table',
		rowConfig: {
			isHover: true
		}
	})

	// 装修类型字典
	const fitmentTypes = ref([])

	/**
	 * 添加小区
	 */
	const community = ref<Community>({})
	const onClickToAddCommunity = () => {
		if (house.value.cityId) {
			const city = findSelf(cities.value, house.value.cityId)
			community.value = {
				cityId: city.id,
				cityName: city.name,
				name: community.value.name,
				regionCode: city.regionCode
			}

			visibles.map = true
		}
	}

	/**
	 * 新增小区地图对话框关闭
	 */
	const communityMapClose = () => {
		if (community.value.id) {
			communities.value.push({...community.value})
			house.value.communityId = community.value.id
		}
		community.value = {}
	}

	const roomsTable = ref<VxeTableInstance>()
	const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	/**
	 * 添加子间
	 */
	const onClickToAddRoom = () => {
		const room = defaultRoom(),
			rooms = house.value.roomList || []

		room.roomName = chars.charAt(rooms.length)
		rooms.push(room)
		house.value.roomList = rooms
		roomsTable.value?.reloadData(rooms)
	}

	/**
	 * 删除子间
	 */
	const onClickToDelRoom = (room: HouseRoom, index: number) => {
		Modal.confirm({
			width: 470,
			title: '系统提示',
			content: () =>
				createVNode('div', {}, [
					createVNode('div', {innerHTML: '请确定相关房间的在租合约、固定资产、智能设备已清空', class: ''}),
					createVNode('div', {innerHTML: '房间删除后无法恢复, 确定删除', style: 'color:red;'})
				]),
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			okText: '删除',
			okType: 'danger',
			async onOk() {
				if (room.houseRoomId) {
					await houseApi.removeHouseRoom(room.houseRoomId)
				}
				const rooms = house.value.roomList || []
				rooms.splice(index, 1)
				house.value.roomList = [...rooms]
			}
		})
	}

	/**
	 * 保存房源基础信息
	 */
	const saveHouseBase = (next?: boolean) => {
		form.value
			?.validate()
			.then(async () => {
				// 82308字典修改
				if (house.value.id && (await isDisabledF())) return

				loading.save = true
				houseApi[house.value.id ? 'updateHouseBasicInfo' : 'addHouseBasicInfo'](house.value)
					.then(({data}) => {
						if (data && !house.value.id) {
							house.value.id = data
							house.value.housePid = data
						}
						message.success('保存成功')
						originHouse.value.transform = false
						if (next) {
							emits('next')
						}
					})
					.finally(() => (loading.save = false))
			})
			.catch(({errorFields}) => {
				form.value?.scrollToField(errorFields[0].name, {
					behavior: 'smooth'
				})
			})
	}

	/* 判断选择的字典是否被禁用 */
	// / 82308字典修改
	const isDisabledF = async () => {
		let temp = false
		let typesList: any = []
		typesList = await settingApi.getDicListByPid(DIC_PID_MAP['HOUSE@DECORTYPE'])
		if (typesList.data?.every((e: any) => e?.id !== house.value.fitmentType)) {
			temp = true
			return message.error('选项已禁用，请选择其他选项！')
		}
		return temp
	}
</script>

<style lang="less" scoped>
	.house-form-base {
		.custom-radio-group {
			display: flex;
			justify-content: space-between;

			label {
				width: 25%;
				margin-right: 15px;
			}
			label:nth-child(4) {
				width: 25%;
				margin-right: 0px;
			}
		}

		:deep(.ant-form-item) {
			.ant-input-prefix {
				color: inherit;
			}
		}

		.ant-skeleton {
			width: 100%;
		}

		:deep(.house-room-table) {
			td {
				padding: 1px !important;

				> div {
					padding: 0;
				}
			}

			.ant-form-item {
				margin: 0;

				input {
					text-align: center;
				}

				.ant-input,
				.ant-picker,
				.ant-input-number,
				.ant-select-selector,
				.ant-input-affix-wrapper {
					border-radius: 0;
				}

				.ant-form-item-explain {
					display: none;
				}
			}
		}

		:deep(.room-table-validator) {
			.ant-form-item-control-input {
				display: none;
			}
		}
	}
</style>
